import React, { useState, useEffect, useMemo } from 'react';
import { Form, Button, Alert, Input, InputNumber, message, Select } from 'antd';
import CommonModal from '@/components/CommonModal';
import CommonLoading from '@/components/CommonLoading';
import LeftContent from './LeftContent';
import RightContent from './RightContent';
import PreviewModal from './PreviewModal';
import { printCard } from '@/utils/print.jsx';
import { addOp, updateOp, queryDefaultTemplate } from '../service';
import { isEmpty } from 'lodash';
import { platformTypeName } from '@/utils/config';
import styles from './index.module.less';

const { Option } = Select;

const initTemplateData = {
  templateName: '',
  totalWidth: 50,
  totalHeight: 80,
  templateValue: [],
};

const titleMap = {
  1: '编辑',
  3: '复制',
  4: '新增',
};

const DragDropModal = ({
  visible,
  source,
  shopList,
  attrList,
  sizeScale,
  handleOk,
  handleCancel,
}) => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [templateData, setTemplateData] = useState({}); //面单模版数据
  const [currId, setCurrId] = useState(undefined); //当前操作对应数据框id
  const [isPreview, setPreview] = useState(false); //预览弹窗

  //模版名称
  const {
    templateName,
    totalWidth,
    totalHeight,
    templateValue = [],
  } = templateData;

  const disabled = useMemo(() => {
    //禁用修改名称
    if (visible == 1 && source.isDefault == 1) {
      //默认模板编辑的时候
      return false;
    } else {
      return true;
    }
  }, [source]);

  //获取商品和订单打印项
  useEffect(() => {
    if (visible) {
      setTemplateData(source ? source : initTemplateData);
    }
  }, [visible]);

  useEffect(() => {
    form.resetFields();
    // console.log(templateData)
  }, [templateData]);

  //获取默认模板
  const getDefaultTemplate = async () => {
    setLoading(true);
    const { success, data = {} } = await queryDefaultTemplate();
    const { templateValue } = data;
    if (success) {
      setTemplateData({
        ...templateData,
        templateValue: templateValue ? JSON.parse(templateValue) : [],
      });
    }
    setLoading(false);
  };

  //点击保存
  const handleSave = () => {
    form.validateFields().then((val) => {
      saveTemplate({
        ...templateData,
        ...val,
        storeId: val.storeId ? val.storeId.join(',') : undefined,
        templateValue: JSON.stringify(templateValue),
      });
    });
  };

  //提交保存
  const saveTemplate = async (val) => {
    setLoading(true);
    let res;
    if (visible == 1) {
      //编辑走更新接口
      res = await updateOp(val);
    } else {
      //新增
      if (visible == 3) {
        //复制
        val.id = undefined;
      }
      res = await addOp(val);
    }
    const { success } = res;
    if (success) {
      message.success('操作成功');
      handleOk();
      onCancel();
    }
    setLoading(false);
  };

  //点击预览
  const handlePreview = () => {
    form.validateFields().then((val) => {
      if (totalWidth && totalHeight) {
        setPreview(true);
        // printCard({type:1,data:{...templateData, templateValue:JSON.stringify(templateData.templateValue)}})
      } else {
        message.error();
        ('请先设置模板尺寸！');
      }
    });
  };

  //左侧展示区
  const LeftContentProps = {
    currId,
    attrList,
    sizeScale,
    templateData,
    updateData(val) {
      setTemplateData(val);
    },
    updateId(val) {
      setCurrId(val);
    },
  };

  //右侧展示区
  const RightContentProps = {
    currId,
    attrList,
    templateData,
    updateData(val) {
      setTemplateData(val);
    },
    updateId(val) {
      setCurrId(val);
    },
  };

  //px 单位级别
  const modalWidth = useMemo(() => {
    if (totalWidth) {
      const comp = totalWidth * sizeScale + 372;
      return comp > 700 ? comp : 700;
    } else {
      return 700; //保证表单inline
    }
  }, [totalWidth]);

  //编辑区域
  const editHeight = useMemo(() => {
    if (totalHeight) {
      const comp = totalHeight * sizeScale;
      return comp > 300 ? comp : 300;
    } else {
      return 300;
    }
  }, [totalHeight]);

  const handlechangeName = () => {
    form.validateFields(['templateName']).then((res) => {
      const { templateName } = res;
      setTemplateData({
        ...templateData,
        templateName,
      });
    });
  };

  //弹窗modal 表单更改
  const handlechange = (type, value) => {
    let content = '';
    if (Number(value)) {
      const reg = /^([1-9]{1}|[1-9]{1}[0-9]{1}|1[0-9]{1}[0-9]{1}|200)$/;
      if (!reg.test(value)) {
        if (value > 200) {
          content = '最大不可超过200mm！';
        } else {
          content = '请正确设置模板尺寸！';
        }
      }
    } else if (value === 0) {
      content = '请设置模板尺寸！';
    } else {
      content = '请正确设置模板尺寸！';
    }
    setTimeout(() => {
      setTemplateData({
        ...templateData,
        [type]: formatInputNumber(form.getFieldValue([type])),
      });
    });
    content && message.error({ content });
  };

  const formatInputNumber = (value) => {
    if (value) {
      if (value.toString().includes('.')) {
        return value.toString().split('.')[0] - 0;
      }
      return value;
    } else {
      return 1;
    }
  };

  //预览弹窗 props
  const PreviewModalProps = {
    sizeScale,
    visible: isPreview,
    source: templateData,
    handleCancel() {
      setPreview(false); //关闭 弹窗
    },
  };

  const onCancel = () => {
    setTemplateData([]);
    handleCancel();
  };

  const optionStore =
    !isEmpty(shopList) &&
    shopList.map((d) => (
      <Option key={d.id} value={`${d.id}`}>
        {d.storeName}【{platformTypeName[d.type]}】
      </Option>
    ));

  return (
    <CommonModal
      title={`${titleMap[visible]}合格证模板`}
      visible={'visible'}
      onCancel={onCancel}
      maxHeight="1000px"
      width={modalWidth}
      footer={[
        <Button key="cancel" onClick={onCancel}>
          取消
        </Button>,
        <Button key="look" onClick={handlePreview}>
          预览
        </Button>,
        <Button key="save" onClick={handleSave} type="primary">
          保存
        </Button>,
      ]}
    >
      <Alert
        message="合格证模板的打印效果以实际打印机打印效果为准，预览仅作为参考"
        type="info"
        style={{ marginBottom: '12px' }}
      />

      <Form
        name="qualification-select-form"
        form={form}
        layout="inline"
        initialValues={{
          templateName,
          totalWidth,
          totalHeight,
          storeId:
            source && source.storeId && visible == 1
              ? source.storeId.split(',')
              : [],
        }}
      >
        <Form.Item
          name="templateName"
          label="模版名称"
          rules={[
            { required: true, message: '请输入模版名称' },
            { max: 30, message: '最多输入30个字符！' },
          ]}
        >
          <Input
            style={{ width: '140px', marginRight: '30px' }}
            placeholder="请输入模版名称"
            onBlur={() => handlechangeName()}
          />
        </Form.Item>
        <Form.Item
          label="模板宽高(毫米)"
          className={styles.labelReqire}
          style={{ display: 'inline-flex' }}
        >
          <div style={{ display: 'flex' }}>
            <Form.Item name="totalWidth">
              <InputNumber
                min={1}
                max={200}
                onBlur={(e) => handlechange('totalWidth', e.target.value)}
              />
            </Form.Item>
            <span style={{ marginRight: 16 }}>X</span>
            <Form.Item name="totalHeight">
              <InputNumber
                min={1}
                max={200}
                onBlur={(e) => handlechange('totalHeight', e.target.value)}
              />
            </Form.Item>
          </div>
        </Form.Item>
        <Form.Item
          style={{ margin: '8px 0 0 12px' }}
          label="请选择店铺"
          name="storeId"
        >
          <Select
            showSearch
            placeholder="请选择"
            optionFilterProp="children"
            mode="multiple"
            allowClear={true}
            style={{ width: 346 }}
            // style={{ margin: '8px 0 0 12px' }}
            maxTagCount={1}
            disabled={disabled}
          >
            {optionStore}
          </Select>
        </Form.Item>
      </Form>
      <Button
        style={{ margin: '12px 0 8px 8px' }}
        onClick={() => getDefaultTemplate()}
      >
        合格证模板
      </Button>
      <div>
        <div
          style={{
            display: 'flex',
            marginTop: '16px',
            justifyContent: 'space-around',
            minHeight: 300,
            height: editHeight,
          }}
        >
          <LeftContent {...LeftContentProps} />
          <RightContent {...RightContentProps} />
        </div>
      </div>
      {isPreview && <PreviewModal {...PreviewModalProps} />}
      <CommonLoading loading={loading} />
    </CommonModal>
  );
};

export default DragDropModal;
